package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsKeywordMapper;
import com.qf.pojo.DtsKeyword;
import com.qf.service.DtsKeywordService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * projectName:workspace_6
 * author:hyn
 * time:2021/12/5 17:18
 * description:
 */
@Service
public class DtsKeywordServiceImpl implements DtsKeywordService {
    @Autowired
    private DtsKeywordMapper keywordMapper;
    //关键词列表
    @Override
    public IPage<DtsKeyword> findKeyWordAllList(String keyword, String url, Integer page, Integer limit, String sort, String order) {
        IPage<DtsKeyword> ipage = new Page(page,limit);
        QueryWrapper<DtsKeyword> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(keyword)){
            wrapper.like("keyword",keyword);
        }
        if(!StringUtils.isEmpty(url)){
            wrapper.like("url",url);
        }
        wrapper.eq("deleted",false);
        if("asc".equals(order)){
            wrapper.orderByAsc(sort);
        }else{
            wrapper.orderByDesc(sort);
        }
        return keywordMapper.selectPage(ipage, wrapper);

    }
    //关键词添加
    @Override
    public Object insert(DtsKeyword keyword) {
        LambdaQueryWrapper<DtsKeyword> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsKeyword::getKeyword,keyword.getKeyword());
        if(keywordMapper.selectOne(wrapper) != null){
            return ResponseUtil.fail(-1,"关键词已存在");
        }
        keyword.setAddTime(new Date());
        keyword.setDeleted(false);
        return keywordMapper.insert(keyword) > 0 ? ResponseUtil.ok(keyword) : ResponseUtil.fail(-1,"添加失败");
    }
    //关键词修改
    @Override
    public Object update(DtsKeyword keyword) {
        if(!keywordMapper.selectById(keyword).getKeyword().equals(keyword.getKeyword())){
            LambdaQueryWrapper<DtsKeyword> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DtsKeyword::getKeyword,keyword.getKeyword());
            if(keywordMapper.selectOne(wrapper) != null){
                return ResponseUtil.fail(-1,"关键词已存在");
            }
        }
        keyword.setUpdateTime(new Date());
        keyword.setDeleted(false);
        return keywordMapper.updateById(keyword) > 0 ? ResponseUtil.ok(keyword) : ResponseUtil.fail(-1,"修改失败");
    }
    //关键词删除
    @Override
    public Object delete(DtsKeyword keyword) {
        return keywordMapper.deleteById(keyword) > 0 ? ResponseUtil.ok(keyword) : ResponseUtil.fail(-1,"删除失败");

    }
}
